import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { generateSign } from '@/utils/signature'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  if (store.getters.token) {
    config.headers['token'] = getToken() // 让每个请求携带token-- ['token']为自定义key 请根据实际情况自行修改
  }
  if (process.env.ENV_ROUTE) {
    config.headers['env'] = process.env.ENV_ROUTE
  }
  config.headers['appCode'] = process.env.APP_CODE // 让每个请求携带appId,appId为系统分发的
  const sign = generateSign(process.env.KEY, process.env.APP_CODE)
  config.headers['sign'] = sign
  return config
}, error => {
  // 对请求错误做些什么
  console.log(error) // for debug
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    var res = response.data
    if (!res) {
      res = {
        success: false,
        msg: '请求接口异常, 请联系管理员'
      }

      MessageBox({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })

      return new Promise(() => {})
    }

    if (res.code != 1) {
      if (res.errorCode === 118000001 ||res.errorCode === 118000014 || res.errorCode === 118000015 || res.errorCode === 118000016) {
        MessageBox.confirm(res.msg, '确定登出', {
          showClose: false,
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else {
        MessageBox({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      // success
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    MessageBox({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
  })

export default service
